package org.robot.scm.platform.server.handler;

import static org.robot.scm.platform.server.LockKey.VERIFY_KEY;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.util.Map;
import java.util.Objects;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.infra.RedisCacheHelper;
import org.robot.scm.utils.StreamUtils;

@Slf4j
@NoArgsConstructor
public class GlobeInterceptor extends BaseHandler implements HttpHandler {


    private Map<String, BaseHandler> handlerMap;

    public GlobeInterceptor(Map<String, BaseHandler> handlerMap) {
        this.handlerMap = handlerMap;
    }

    @Override
    public String getUri() {
        return "/globe";
    }

    @Override
    public void handle(HttpExchange exchange) {
        try {
            super.noCache(exchange);
            super.allowCors(exchange);
            Map<String, String> queryMap = queryToMap(exchange.getRequestURI().getQuery());
            String authCode = queryMap.get("auth");
            String mapperKey = StreamUtils.filterOne(handlerMap.keySet(), e -> exchange.getRequestURI().getPath().contains(e));
            BaseHandler baseHandler = handlerMap.get(mapperKey);
            if (Objects.isNull(baseHandler)) {
                sendFailureResponse(exchange, exchange.getRequestURI().getPath() + " 404");
                return;
            }

            HttpHandler httpHandler = (HttpHandler) baseHandler;
            if (!baseHandler.needAuth()) {
                httpHandler.handle(exchange);
                return;
            }

            if (StringUtils.isBlank(authCode)) {
                sendFailureResponse(exchange, "请输入授权码");
                return;
            }

            // 万能授权码
            if (StringUtils.equals("d249159b3fa944e0b2457a6694930f47", authCode)) {
                httpHandler.handle(exchange);
                return;
            }

            String code = RedisCacheHelper.get(VERIFY_KEY);
            if (StringUtils.isBlank(code)) {
                sendFailureResponse(exchange, "授权码过期");
                return;
            }

            if (!StringUtils.equals(code, authCode)) {
                sendFailureResponse(exchange, "授权码错误");
                return;
            }

            httpHandler.handle(exchange);
        } catch (Exception e) {
            log.error("http interceptor error", e);
            sendFailureResponse(exchange, e.getMessage());
        }
    }
}
